//
//  TJAppealController.m
//  Teleport
//
//  Created by hc-101 on 2020/6/19.
//  Copyright © 2020 xtjun. All rights reserved.
//

#import "TJAppealController.h"
#import "TJSelectPhotoView.h"
#import "YLSelectPhotoCell.h"


@interface TJAppealController ()<QMUITextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) QMUITextView *textView;

@property (weak, nonatomic) TJSelectPhotoView *certificateView;
@property (weak, nonatomic) UIButton *determineButton;
@property (strong, nonatomic) NSMutableArray *urls;

@end

@implementation TJAppealController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.title = @"申诉".localizedString;
    
    UILabel *reasonLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(15) color:UIColor.blackColor title:@"申诉理由".localizedString textAlignment:NSTextAlignmentLeft];
    [reasonLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.offset(KNavBarHight + 20);
    }];
    
    _urls = @[].mutableCopy;
    
    self.textView = [[QMUITextView alloc] initWithFrame:CGRectMake(0, KNavBarHight + 10, KScreenWidth, 200)];
    self.textView.backgroundColor = UIColor_Hex(0xF4F9FF);
    self.textView.placeholder = @"请输入申诉理由".localizedString;
    self.textView.font = UIFont_Px(15);
    self.textView.placeholderColor = UIColor_Hex(0x999999);
    [self.view addSubview:_textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(reasonLabel.mas_bottom).offset(12);
        make.height.offset(120);
    }];
    
    UILabel *certificateLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(15) color:UIColor.blackColor title:@"申诉凭证".localizedString textAlignment:NSTextAlignmentLeft];
    [certificateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(reasonLabel);
        make.top.equalTo(_textView.mas_bottom).offset(20);
    }];
    
    
    weakify(self)
    TJSelectPhotoView *certificateView = [TJSelectPhotoView tj_addToView:self.view];
    certificateView.backgroundColor = UIColor.whiteColor;
    
    certificateView.datas = @[[TJSelectPhotoModel selectPhotoModel:nil isAdd:YES isShowDelete:NO]].mutableCopy;;
    [certificateView setDidSelectItemAtIndexPathBlock:^(TJSelectPhotoModel *model) {
        strongify(self)
        
        NSLog(@"%@",model);
        if (model.isAdd) {
            [self showImagePickerController];
        }
    }];
    
    weakify(certificateView)
    [certificateView setDidRemoveItemAtIndexPathBlock:^(TJSelectPhotoModel *model) {
        [weakcertificateView.datas removeObject:model];
        [weakcertificateView resetData];
        [self textViewDidChange:self.textView];
        NSLog(@"setDidRemoveItemAtIndexPathBlock = %@",model);
    }];
    
    [certificateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(certificateLabel.mas_bottom).offset(4);
        make.height.offset(120);
    }];
    
    
    UIButton *determineButton = [UIButton buttonWithSuperView:self.view font:UIFont_Px(18) color:UIColor.whiteColor title:@"确定".localizedString];
    determineButton.backgroundColor = UIColor_Hex(0x2C6CC7);
    [determineButton shearRoundedCornersWithRadiu:22];
    [determineButton addTarget:self action:@selector(didClickDetermineButton) forControlEvents:UIControlEventTouchUpInside];
    [determineButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-38);
        make.left.offset(38);
        make.height.offset(44);
        make.centerX.offset(0);
        make.top.equalTo(certificateView.mas_bottom).offset(50);
    }];
    
    _determineButton = determineButton;
    _certificateView = certificateView;
    self.textView.delegate = self;
    
    [self textViewDidChange:_textView];
}

- (void)didClickDetermineButton {
    
    NSMutableDictionary *parameters = @{
        @"userId": TJUserInfo.readInfo.userId,
        @"priceOrderId": _orderId ?: @""
    }.mutableCopy;
    
    if (_urls.count) {
        
        for (int i = 0; i < _urls.count; i++) {
            
            [parameters setValue:_urls[i] forKey:[NSString stringWithFormat:@"url%d",(i+1)]];
            
        }
    }
    
    

    [parameters setValue:_textView.text ?: @"" forKey:@"msg"];
  
    
    [self showloading];
    [TJNetworking.shareNetworking POSTNew:@"otc/order/appeal" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        [self hiddenloading];
        self.textView.text = nil;
        [TJHud showAutoHideMessage:responseObject[@"msg"]];
        if (self.complete) {
            self.complete();
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    } failure:^(NSError * _Nonnull error) {
        [self hiddenloading];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
    
}

- (void)textViewDidChange:(UITextView *)textView {
    [_urls removeAllObjects];
    [self.certificateView.datas enumerateObjectsUsingBlock:^(TJSelectPhotoModel *model, NSUInteger idx, BOOL * _Nonnull sectionStop) {
        if (model.isShowDelete && model.url) {
            [_urls addObject:model.url];
        }
    }];
    
    _determineButton.userInteractionEnabled = _textView.text.length || _urls.count ;
    _determineButton.backgroundColor = (_determineButton.userInteractionEnabled) ? UIColor.tj_mainColor : [UIColor_Hex(0x666666) colorWithAlphaComponent:0.3];
    
}

- (void)showImagePickerController {
    
    UIAlertController * ActionSheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * CancelAlertAction = [UIAlertAction actionWithTitle:@"取消".localizedString style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction * CameraAlertAction = [UIAlertAction actionWithTitle:@"拍照".localizedString style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
            
            UIImagePickerController * ipc = [[UIImagePickerController alloc] init];
            ipc.delegate = self;
            ipc.sourceType = sourceType;
            [self presentViewController:ipc animated:YES completion:nil];
        }
    }];
    
    UIAlertAction * PhotoAlbumAlertAction = [UIAlertAction actionWithTitle:@"相册".localizedString style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController * ipc = [[UIImagePickerController alloc] init];
        ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        ipc.modalPresentationStyle = UIModalTransitionStyleCoverVertical;
        ipc.delegate = self;
        ipc.navigationBar.tintColor = [UIColor blackColor];
        ipc.navigationBar.translucent = NO;
        [self presentViewController:ipc animated:YES completion:nil];
    }];
    
    [ActionSheetController addAction:CancelAlertAction];
    [ActionSheetController addAction:CameraAlertAction];
    [ActionSheetController addAction:PhotoAlbumAlertAction];
    
    [self presentViewController:ActionSheetController animated:YES completion:nil];
}

#pragma mark   -----UIImagePickerController代理方法-----
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *tempImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    tempImage = [UIImage imageWithData: [UIImage lubanCompressImage:tempImage]];
    
    [self showloading];
    
    
    [TJNetworking.shareNetworking updataImageWithImage:tempImage success:^(NSDictionary * resp, id data) {
        [self hiddenloading];
        
        TJSelectPhotoModel *model = [TJSelectPhotoModel selectPhotoModel:tempImage isAdd:NO isShowDelete:YES];
        model.url = data;
        [self.certificateView.datas insertObject:model atIndex:self.certificateView.datas.count - 1];
        self.certificateView.datas = self.certificateView.datas;
        [self textViewDidChange:self.textView];
    } failure:^(NSError *errpr) {
        [self hiddenloading];
        [TJHud showAutoHideMessage:@"上传失败, 请稍后再试".localizedString];
    }];
    
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}




@end
